<?php

class MailComponent extends Object {

	public function __construct() {
		App::import('Core', 'Controller');
		App::import('Component', 'Email');

		$this->Controller =& new Controller();
		$this->Email =& new EmailComponent(null);
		$this->Email->initialize($this->Controller);
   		$this->reset();
	}

	public function sendMail($to, $subject, $template, $data){
		$this->Email->to = $to;
		$this->Email->template = $template;
		$this->Email->subject = $subject;
		foreach($data as $key => $value){
			$this->Controller->set($key, $value);
		}
		$this->send();
	}

	private function send() {
		$sent = $this->Email->send();
		if (!empty($this->Email->smtpError)) {
			$this->log('EMAIL ERROR: ' . $this->Email->smtpError, LOG_ERROR);
		}
		$this->reset();
		return $sent;
	}

	public function _set($key, $value){
		$this->Email->{$key} = $value;
	}

	function reset(){
		$this->Email->reset();
		$this->Email->from = Configure::read('SMTP.sender');
		$this->Email->smtpOptions = array(
				        'port'=>Configure::read('SMTP.port'),
				        'timeout'=>Configure::read('SMTP.timeout'),
				        'auth' => true,
				        'host' => Configure::read('SMTP.host'),
				        'username'=> Configure::read('SMTP.email'),
				        'password'=> Configure::read('SMTP.password')
   		);

   		$this->Email->delivery = 'smtp';
   		$this->Email->sendAs = 'both';
	}
}

?>